package cam.app;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.media.FaceDetector.Face;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.media.FaceDetector;
import android.webkit.WebView;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashSet;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

public class MainActivity extends Activity {
    
    private Camera mCamera;
    private CameraPreview mPreview;
    private Button mButton;
    private Activity mActivity;
    private WebView mWebView;
    private FrameLayout mFrameLayout;
    private boolean mState = false;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = this;
        mWebView = new WebView(this);
        mFrameLayout = new FrameLayout(this);

        // Create an instance of Camera
        mCamera = getCameraInstance();
        
        mCamera.setDisplayOrientation(90);

        // Create our Preview view and set it as the content of our activity.
        mPreview = new CameraPreview(this, mCamera);
        mFrameLayout.addView(mPreview);
        setContentView(mFrameLayout);
        
        mFrameLayout.setOnClickListener(new OnClickListener() {
            
            public void onClick(View arg0) {
                mCamera.takePicture(null, null,
                        new Camera.PictureCallback() {
                            
                            public void onPictureTaken(byte[] arg0, Camera arg1) {
                                String url = GetMatchUrl(arg0);
                                
                                mWebView.loadUrl(url);
                                mState = true;
                                mActivity.setContentView(mWebView);                                
                            }
                        });
            }
        });
    }
       
    private String GetMatchUrl(byte[] bytes) {
        
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        DataInputStream inputStream = null;
        
        String urlServer = "http://192.168.1.101:8081/hello/GetMatchURL";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        
        try {
            
            URL url = new URL(urlServer);
            connection = (HttpURLConnection) url.openConnection();

// Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

// Enable POST method
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Length", bytes.length + "");
            
            outputStream = new DataOutputStream(connection.getOutputStream());
            
            int size = outputStream.size();
            outputStream.write(bytes, 0, bytes.length);
            outputStream.flush();
            
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();
            
            DataInputStream dataInputStream = new DataInputStream(connection.getInputStream());
            String result = dataInputStream.readLine();
            JSONObject json = new JSONObject(result);

            //fileInputStream.close();
            outputStream.close();
            dataInputStream.close();
            
            return json.getString("GetMatchUrlResult");
        } catch (Exception ex) {
            return ex.getMessage();
        }
        
    }

    /** A safe way to get an instance of the Camera object. */
    public static Camera getCameraInstance() {
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance
        } catch (Exception e) {
            // Camera is not available (in use or does not exist)
            Log.e("", "", e);
        }
        return c; // returns null if camera is unavailable
    }    
    
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //Handle the back button
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mState) {
                mState = false;
                
                mCamera.startPreview();
                mActivity.setContentView(mFrameLayout);
            } else {
                //Ask the user if they want to quit
                new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit").setMessage("Are you sure you want to leave?").setNegativeButton(android.R.string.cancel, null).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // Exit the activity
                        mActivity.finish();
                    }
                }).show();
            }
            // Say that we've consumed the event
            return true;
        }
        
        return super.onKeyDown(keyCode, event);
    }
    
     @Override
    public void onDestroy() 
     {
         if (mCamera != null)
             mCamera.release();
          
         super.onDestroy();
     }
    
    
}


